//
//  Extesion.swift
//  Teamo
//
//  Created by mdzz on 2021/12/9.
//

import Foundation


protocol Countable {
    var count: Int { get }
    var isEmpty: Bool { get }
}

extension Data: Countable {}
extension Array: Countable {}
extension String: Countable {}
extension Dictionary: Countable {}

extension Optional where Wrapped: Countable {
    /// The Array's count (or 0 if the array is nil).
    internal var count: Int {
        return self?.count ?? 0
    }

    internal var isEmpty: Bool {
        return self?.isEmpty ?? true
    }
}

extension Array where Element: Equatable {
    @discardableResult
    public mutating func remove(_ object: Element) -> Element? {
        guard let index = firstIndex(of: object) else {
            return nil
        }
        return remove(at: index)
    }
}

extension Array {
    public var toJSON: String {
        let defaultJSON = "[]"
        guard let data = try? JSONSerialization.data(withJSONObject: self) else {
            return defaultJSON
        }

        return String(data: data, encoding: .utf8) ?? defaultJSON
    }
}

extension Dictionary {
    public var toJSON: String {
        let defaultJSON = "{}"
        guard let data = try? JSONSerialization.data(withJSONObject: self) else {
            return defaultJSON
        }

        return String(data: data, encoding: .utf8) ?? defaultJSON
    }
}

extension String {
    public var asJSON: AnyObject? {
        if let data = self.data(using: .utf8, allowLossyConversion: false) {
            /// Will return an object or nil if JSON decoding fails
            let message = try? JSONSerialization.jsonObject(with: data)
            return message as AnyObject?
        } else {
            /// Lossless conversion of the string was not possible
            return nil
        }
    }
}
